package com.wdl.fm.system.user.service.impl;

import com.wdl.fm.common.dao.SysUserMapper;
import com.wdl.fm.common.dao.SysUserRoleMapper;
import com.wdl.fm.common.entity.tree.TreeNodeSimple;
import com.wdl.fm.common.exception.LoginException;
import com.wdl.fm.common.model.*;
import com.wdl.fm.common.utils.ApplicationUtils;
import com.wdl.fm.common.utils.PasswordHash;
import com.wdl.fm.core.orm.mybatis.Page;
import com.wdl.fm.system.authority.service.PermissionService;
import com.wdl.fm.system.authority.service.RoleService;
import com.wdl.fm.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/6/6.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public List<SysRole> getRolesByUserID(String id) {
        List<SysRole> list = new ArrayList<>();

        list.addAll(roleService.getRoles(getUserRoles(id)));

        return list;
    }

    @Override
    public List<SysRole> getRolesByUserID(String id, String name) {
        if ("admin".equals(name))
            return roleService.getAllRoles();
        return getRolesByUserID(id);
    }

    @Override
    public List<SysPermission> getPermissionsByUserID(String id) {
        List<SysPermission> list = new ArrayList<>();

        List<SysUserRole> userRoles = getUserRoles(id);
        for (SysUserRole info : userRoles) {
            list.addAll(roleService.getPermissionsByRoleID(info.getRoleId()));
        }

        return list;
    }

    @Override
    public List<SysPermission> getPermissionsByUserID(String id, String name) {
        if ("admin".equals(name))
            return permissionService.getAllPermissions();
        return getPermissionsByUserID(id);
    }

    @Override
    public SysUser getUserByName(String name) {
        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameEqualTo(name);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);

        if (sysUsers != null && sysUsers.size() > 0)
            return sysUsers.get(0);

        return null;
    }

    @Override
    public List<SysUserRole> getUserRoles(String userID) {
        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(userID);
        return sysUserRoleMapper.selectByExample(sysUserRoleExample);
    }

    @Override
    public void authenticationUser(String name, String pwd) throws LoginException {
        SysUser user = getUserByName(name);
        if (user == null)
            throw new LoginException("用户不存在");

        String pwdquery = "1000:" + user.getSalt() + ":" + user.getPassword();
        try {
            if (!PasswordHash.validatePassword(pwd, pwdquery))
                throw new LoginException("密码错误");
        } catch (NoSuchAlgorithmException e) {
            throw new LoginException("密码错误");
        } catch (InvalidKeySpecException e) {
            throw new LoginException("密码错误");
        }
    }

    @Override
    public Page<SysUser> getPageList(Page<SysUser> page, String keyword) {
        if (keyword == null)
            keyword = "";

        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameLike("%" + keyword + "%");
        page.setResult(sysUserMapper.selectByExample(page, example));

        return page;
    }

    @Override
    public SysUser getUserByID(String id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean addUser(SysUser user) {
        user.setCreatetime(new Date());
        user.setId(ApplicationUtils.getUUID());

        try {
            String hash = PasswordHash.createHash(user.getPassword());
            String[] split = hash.split(":");
            user.setSalt(split[1]);
            user.setPassword(split[2]);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            return false;
        }

        return sysUserMapper.insert(user) > 0;
    }

    @Override
    public boolean updateUser(SysUser user) {
        return sysUserMapper.updateByPrimaryKeySelective(user) > 0;
    }


    @Override
    public boolean delUser(String id) {
        return sysUserMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public String delUsers(List<String> ids) {
        int count = 0;
        for (String id : ids) {
            if (delUser(id))
                count++;
        }
        return "成功删除" + count + "条数据，失败" + (ids.size() - count) + "条";
    }

    @Override
    public boolean resetPwd(String id, String pwd) {
        try {
            String[] split = PasswordHash.createHash(pwd).split(":");
            SysUser user = new SysUser();
            user.setId(id);
            user.setSalt(split[1]);
            user.setPassword(split[2]);

            return sysUserMapper.updateByPrimaryKeySelective(user) > 0;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<TreeNodeSimple> getAllRoleTreeUserChecked(String userID) {
        List<TreeNodeSimple> tree = new ArrayList<>();

        List<SysRole> allRoles = roleService.getAllRoles();
        TreeNodeSimple node;
        for (SysRole info : allRoles) {
            node = new TreeNodeSimple();
            node.setId(info.getId());
            node.setName(info.getRolename());
            node.setpId(null);
            node.setChecked(hasRole(userID, info.getId()));

            tree.add(node);
        }

        return tree;
    }

    @Override
    public boolean hasRole(String userID, String roleID) {
        SysUserRoleExample example = new SysUserRoleExample();
        example.createCriteria().andUserIdEqualTo(userID).andRoleIdEqualTo(roleID);
        return sysUserRoleMapper.selectByExample(example).size() > 0;
    }

    @Override
    public boolean addUserRole(String userID, String roleID) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(roleID);
        sysUserRole.setUserId(userID);
        return sysUserRoleMapper.insert(sysUserRole) > 0;
    }

    @Override
    public boolean delUserRole(String userID, String roleID) {
        SysUserRoleExample example = new SysUserRoleExample();
        example.createCriteria().andUserIdEqualTo(userID).andRoleIdEqualTo(roleID);
        return sysUserRoleMapper.deleteByExample(example) > 0;
    }

    @Override
    public boolean changeUserRole(String userID, String roleID, boolean checked) {
        if (checked) {
            return addUserRole(userID, roleID);
        }

        if (hasRole(userID, roleID))
            return delUserRole(userID, roleID);

        return true;
    }

    @Override
    public boolean changeUserRoleGroup(String userID, String roleID, boolean checked) {

        List<SysRole> listByPid = roleService.getListByPid(roleID);
        for (SysRole info : listByPid)
            changeUserRole(userID, info.getId(), checked);

        return true;
    }


}
